package com.wang.helloandroid.activity;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

import com.wang.helloandroid.R;
import com.wang.helloandroid.service.LocationService;
import com.wang.helloandroid.util.Decrypt;
import com.wang.helloandroid.ws.WSClient;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
	final static String tag = MainActivity.class.getName();
	
	WSClient mWebSocketClient;
	LocationService locationService;

	public void onBtnStartClick(View view)
	{
		final EditText url = (EditText) findViewById(R.id.main_input);
		
		getLocationInformation();
		/*AsyncTask<String, Object, Object> locationTask = new AsyncTask<String, Object, Object>() {
			@Override
			protected Object doInBackground(String... urls) {
				connectWebSocket(urls[0]);
				return null;
			}
		};
		locationTask.execute(url.getText().toString());*/

		runOnUiThread(new Runnable() {
		    public void run() 
		    {
		    	connectWebSocket(url.getText().toString());
		    }
		});
	}

	protected void getLocationInformation()
	{
		Toast toast;
		Location p = null;
		try {
			p = locationService.getLocation();
		} catch (InterruptedException e) {
			Log.e(this.getClass().getName(), "We can't wait...");
		}

		if(null == p)
		{
			toast = Toast.makeText(getApplicationContext(), "Cannot get location information",Toast.LENGTH_SHORT);
		}
		else
		{
			toast = Toast.makeText(getApplicationContext(), "Latitude: " + p.getLatitude() + "\nLongitude:" + p.getLongitude(),Toast.LENGTH_LONG);
		}
        toast.show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
		}

		// Get LocationService
		locationService = new LocationService(this, true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container, false);
			return rootView;
		}
	}

	// Websocket Support
	private void connectWebSocket(String connectString) {
		URI uri;
		try {
			uri = new URI(connectString);
		} catch (URISyntaxException e) {
			e.printStackTrace(); 
			return;
		}
		
		try
		{
			if(null == mWebSocketClient || mWebSocketClient.isClosed())
			{
				mWebSocketClient = new WSClient(uri, "jeff", UUID.randomUUID().toString().substring(0, 8))
				{
					@Override
					public void onMessage(String s) {
						final String message = Decrypt.base64Decode(s);
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								TextView textView = (TextView) findViewById(R.id.message);
								textView.setText(message);
							}
						});
					}
				};

				mWebSocketClient.connect();
			}
		}
		catch(Exception e)
		{
			Log.e(tag, null==e.getMessage()?"WebsocketNotConnectedException":e.getMessage());
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == 0) {
			switch (requestCode) {
			case LocationService.REQUEST_CODE_LOCATION_SERVICE:
				String providers = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
				if(TextUtils.isEmpty(providers))
				{
					Toast.makeText(this, "Location is not enabled.", Toast.LENGTH_LONG).show();
				}
				else
				{
					locationService.updateProvider(false);
					Toast.makeText(this, "Location provider " + providers + " is enabled.", Toast.LENGTH_LONG).show();
				}
				break;
				
			default:
                break;
			}
		}
		else if (resultCode == RESULT_CANCELED) {
			Toast.makeText(this, "Operation is canceled.", Toast.LENGTH_LONG).show();
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
}
